#include "DeviceWorker.h"
#include "CopperParticleDevice.h"

DeviceWorker::DeviceWorker(QObject *parent)
    : QObject(parent)
    , m_device(nullptr)
{
}

DeviceWorker::~DeviceWorker()
{
    cleanup();
}

void DeviceWorker::init()
{
    if (!m_device) {
        m_device = new CopperParticleDevice;

        connect(m_device, &CopperParticleDevice::connected,
                this, &DeviceWorker::connected, Qt::QueuedConnection);
        connect(m_device, &CopperParticleDevice::disconnected,
                this, &DeviceWorker::disconnected, Qt::QueuedConnection);
        connect(m_device, &CopperParticleDevice::errorOccurred,
                this, &DeviceWorker::errorOccurred, Qt::QueuedConnection);
        connect(m_device, &CopperParticleDevice::commandCompleted,
                this, &DeviceWorker::onCommandCompleted, Qt::QueuedConnection);
        connect(m_device, &CopperParticleDevice::queryDataReceived,
                this, &DeviceWorker::onQueryDataReceived, Qt::QueuedConnection);

        emit initialized();
    }
}

void DeviceWorker::cleanup()
{
    if (m_device) {
        m_device->disconnectFromDevice();
        delete m_device;
        m_device = nullptr;
    }
}

void DeviceWorker::connectToDevice(const QString &host, quint16 port)
{
    if (!m_device) {
        emit errorOccurred("Device not initialized");
        return;
    }

    if (!m_device->connectToDevice(host, port)) {
        emit errorOccurred("Failed to connect to device");
    }
}

void DeviceWorker::disconnectFromDevice()
{
    if (!m_device) {
        emit errorOccurred("Device not initialized");
        return;
    }
    m_device->disconnectFromDevice();
}

bool DeviceWorker::isConnected() const
{
    return m_device && m_device->isConnected();
}

void DeviceWorker::sendDeviceCommand(DeviceProtocol::IPCCommand command, const QVariantMap &params)
{
    if (!m_device) {
        emit errorOccurred("Device not initialized");
        return;
    }

    // 不再传递 response 指针
    bool success = m_device->sendDeviceCommand(command, params);

    if (!success) {
        emit errorOccurred("Failed to add command to queue");
    }
}

void DeviceWorker::onCommandCompleted(DeviceProtocol::IPCCommand command, bool success, const QVariantMap &responseData)
{
    qDebug() << "命令完成回调 - 命令:" << static_cast<int>(command) << "成功:" << success << "响应数据:" << responseData;

    if (success) {
        // 首先检查是否有执行结果
        if (responseData.contains("exeRtn")) {
            int exeRtn = responseData["exeRtn"].toInt();
            QString exeRtnMessage = responseData["exeRtnMessage"].toString();

            if (exeRtn == 1) {
                // 执行成功
                emit commandResponseReceived(command, true, "命令执行成功");

                // 检查是否有查询数据
                if (responseData.contains("queryData")) {
                    QVariantMap queryData = responseData["queryData"].toMap();
                    qDebug() << "发送数据响应信号 - 命令:" << static_cast<int>(command) << "数据:" << queryData;
                    emit commandDataResponseReceived(command, true, queryData);
                }
            } else {
                // 执行失败
                emit commandResponseReceived(command, false,
                                             QString("命令执行失败: %1").arg(exeRtnMessage));
            }
        }
        // 如果没有执行结果，但直接有查询数据（某些命令可能只有数据响应）
        else if (responseData.contains("queryData")) {
            QVariantMap queryData = responseData["queryData"].toMap();
            qDebug() << "发送数据响应信号（无执行结果）- 命令:" << static_cast<int>(command) << "数据:" << queryData;
            emit commandDataResponseReceived(command, true, queryData);
            emit commandResponseReceived(command, true, "查询成功");
        }
        else {
            // 其他成功情况，但没有查询数据
            emit commandResponseReceived(command, true, "命令执行成功");
        }
    } else {
        // 失败情况
        QString errorMsg = "命令执行失败";
        if (responseData.contains("error")) {
            errorMsg = responseData["error"].toString();
        }
        emit commandResponseReceived(command, false, errorMsg);
    }
}

void DeviceWorker::onQueryDataReceived(DeviceProtocol::IPCCommand command, const QVariantMap &data)
{
    emit queryDataImmediatelyReceived(command, data);
}
